package mess;

import java.util.Set;
import java.util.TreeSet;

public class LeeCode_64_2 {
    public static void main(String[] args) {
        int[][] grid = new int[][]{{1,3,1},{1,5,1},{4,2,1}};
        System.out.println(minPathSum(grid));
    }
    private static int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] result = new int[m][n];
        result[m - 1][n - 1] = grid[m - 1][n - 1];
        boolean flag = true;
        for (int j = n - 1; j >= 0 ; j--) {
            for (int i = m - 1; i >= 0 ; i--) {
                if (flag){
                    flag = false;
                    continue;
                }
                //行边界
                if (i == m - 1){
                    result[i][j] = result[i][j + 1] + grid[i][j];
                }else if (j == n - 1){
                    //列边界
                    result[i][j] = result[i + 1][j] + grid[i][j];
                }else {
                    result[i][j] = Math.min(result[i + 1][j], result[i][j + 1]) + grid[i][j];
                }
            }
        }
        return result[0][0];
    }
}
